package com.fzrskj.cloud.free.core.utils;

import ms.core.tool.StrTool;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * HttpClientUtils.
 *
 * @author wzj.
 *         Created on 2019/04/19 0016.
 */
public class HttpClientUtils {
    public static final String DEFAULT_CHARSET = "UTF-8";

    public static String get(String url) throws IOException {
        return get(url, DEFAULT_CHARSET);
    }

    public static String get(String url, String charset) throws IOException {
        HttpURLConnection con = null;
        try {
            URL u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setUseCaches(false);
            con.setDoInput(true);
            con.setRequestProperty("Connection", "Keep-Alive");

            if (con.getResponseCode() == HttpURLConnection.HTTP_OK
                    || con.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
                StringBuilder sb = new StringBuilder(con.getContentLength() == -1 ? 1024 * 5 : con.getContentLength());
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
                for (String line = br.readLine(); line != null; line = br.readLine()) {
                    sb.append(line);
                }
                return sb.toString();
            }
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        return null;
    }

    /**
     * Http请求.
     * <p>Description: </p>
     * <p>Create Time: 2017/3/16 0016 10:40 </p>
     * @author 910204
     * @param url 请求地址
     * @param request 为null或空字符串时发起GET请求；否则为POST请求，内容为请求体的JSON序列化
     * @return
     * @throws IOException
     */
    public static String request(String url, String request) throws IOException {
        HttpURLConnection con = null;
        try {
            URL u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setUseCaches(false);
            con.setDoInput(true);
            con.setRequestProperty("Connection", "Keep-Alive");
            if (request != null && !"".equals(request)) {
                con.setDoOutput(true);
                con.setRequestMethod("POST");
                con.setRequestProperty("Charset", DEFAULT_CHARSET);
                OutputStream os = con.getOutputStream();
                os.write(request.getBytes(DEFAULT_CHARSET));
                os.flush();
                os.close();
            }

            if (con.getResponseCode() == HttpURLConnection.HTTP_OK
                    || con.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
                StringBuilder sb = new StringBuilder(con.getContentLength() == -1 ? 1024 * 5 : con.getContentLength());
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), DEFAULT_CHARSET));
                for (String line = br.readLine(); line != null; line = br.readLine()) {
                    sb.append(line);
                }
                return sb.toString();
            }
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        return null;
    }

    public static String request(String url, String request, String contentType) throws IOException {
        HttpURLConnection con = null;
        try {
            URL u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setUseCaches(false);
            con.setDoInput(true);
            con.setRequestProperty("Connection", "Keep-Alive");
            if (request != null && !"".equals(request)) {
                con.setDoOutput(true);
                con.setRequestMethod("POST");
                con.setRequestProperty("Charset", DEFAULT_CHARSET);
                con.setRequestProperty("Content-Type", contentType);
                // con.setRequestProperty("Content-Type", "application/json");
                OutputStream os = con.getOutputStream();
                os.write(request.getBytes(DEFAULT_CHARSET));
                os.flush();
                os.close();
            }

            if (con.getResponseCode() == HttpURLConnection.HTTP_OK
                    || con.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
                StringBuilder sb = new StringBuilder(con.getContentLength() == -1 ? 1024 * 5 : con.getContentLength());
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), DEFAULT_CHARSET));
                for (String line = br.readLine(); line != null; line = br.readLine()) {
                    sb.append(line);
                }
                return sb.toString();
            }
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        return null;
    }

    public static Map<String, Object> request(String url, String request, String method, Map<String, String> headerMap)
            throws IOException {
        Map<String, Object> result = new HashMap<String, Object>();
        HttpURLConnection con = null;
        try {
            URL u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setUseCaches(false);
            con.setDoInput(true);
            con.setRequestProperty("Connection", "Keep-Alive");
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                con.setRequestProperty(entry.getKey(), entry.getValue().trim());
            }

            con.setRequestMethod(method);
            con.setRequestProperty("Charset", DEFAULT_CHARSET);
            if (!"GET".equals(method) && !"DELETE".equals(method) && null!=request) {
                con.setDoInput(true);
                con.setDoOutput(true);
                OutputStream os = con.getOutputStream();
                os.write(request.getBytes(DEFAULT_CHARSET));
                os.flush();
                os.close();
            }

            result.put("http_code", con.getResponseCode());
            StringBuilder sb;
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK
                    || con.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
                sb = new StringBuilder(con.getContentLength() == -1 ? 1024 * 5 : con.getContentLength());
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), DEFAULT_CHARSET));
                for (String line = br.readLine(); line != null; line = br.readLine()) {
                    sb.append(line);
                }

            } else {
                sb = new StringBuilder(con.getContentLength() == -1 ? 1024 * 5 : con.getContentLength());
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getErrorStream(), DEFAULT_CHARSET));
                for (String line = br.readLine(); line != null; line = br.readLine()) {
                    sb.append(line);
                }
            }

            String sbString = sb.toString();
            if (StrTool.isBlankStr(sbString)) {
                result.put("response", "");
            } else if (sbString.startsWith("{")) {
                result.put("response", JSONObject.fromObject(sbString));
            } else if (sbString.startsWith("[")) {
                result.put("response", JSONArray.fromObject(sbString));
            } else {
                result.put("response", sbString);
            }
            return result;

        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
    }

    public static String request(String url, String request, String contentType, String authorization,
                                 String requestMethod) throws IOException {
        HttpURLConnection con = null;
        try {
            URL u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setUseCaches(false);
            con.setDoInput(true);
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setDoOutput(true);
            con.setRequestMethod(requestMethod.toUpperCase());
            con.setRequestProperty("Charset", DEFAULT_CHARSET);
            con.setRequestProperty("Content-Type", contentType);
            if (!"".equals(authorization)) {
                con.setRequestProperty("Authorization", authorization);
            }

            if (!isEmpty(request)) {
                OutputStream os = con.getOutputStream();
                os.write(request.getBytes(DEFAULT_CHARSET));
                os.flush();
                os.close();
            }
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK
                    || con.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
                StringBuilder sb = new StringBuilder(con.getContentLength() == -1 ? 1024 * 5 : con.getContentLength());
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), DEFAULT_CHARSET));
                for (String line = br.readLine(); line != null; line = br.readLine()) {
                    sb.append(line);
                }
                return sb.toString();
            }
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        return null;
    }

    static boolean isEmpty(CharSequence s) {
        return s == null || s.length() == 0;
    }
}
